<?php


namespace app\api\services;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\libs\Singleton;

class CodeService
{
    use Singleton;

    /**
     * 阿里云发送短信
     * @param $mobile
     * @param $code
     * @return bool|mixed|string
     * @throws ClientException
     */
    public function sendMsgAli($mobile, $code)
    {
        $msgDate = self::getCodeType();
        if (false == $msgDate) {
            return false;
        }
        AlibabaCloud::accessKeyClient('LTAI5tRPQjNHUVpw2SrvLsyp', '0XLcNpLsZzu0AQyqGiZaWdbwrPBeRe')
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,
                        'SignName' => $msgDate['SignName'],
                        'TemplateCode' => $msgDate['TemplateCode'],
                        'TemplateParam' => json_encode(['code' => $code]),
                    ],
                ])->request();
            $resultArr = $result->toArray();
            if ($resultArr['Code'] == 'OK') {
                return true;
            } else {
                return $resultArr['Message'];
            }
        } catch (ClientException | ServerException $e) {
            return $e->getErrorMessage();
        }

    }

    /**
     * 获取模版
     * @return string[]
     */
    public static function getCodeType(): array
    {
        return [
            'SignName' => '日兮',
            'TemplateCode' => 'SMS_295836108',
        ];
    }
}